import * as fs from "fs";
import * as path from "path";

export class FakedFileReader {
    constructor() {
        this.onload = undefined;
        this.onerror = undefined;
        this.result = undefined;
    }
    readAsText(fakedSlicedFile) {
        this.result = fakedSlicedFile.content;
        if (this.onload) {
            this.onload();
        }
    }
}

export class FakedSliceFile {
    constructor(content) {
        this.content = content;
    }
}
FakedSliceFile.fromFile = function (filePath, startPos, endPos) {
    let readLen = endPos - startPos;
    let buf = Buffer.alloc(readLen);
    let fd = fs.openSync(filePath, 'r');
    fs.readSync(fd, buf, 0, readLen, startPos);
    fs.closeSync(fd);
    return new FakedSliceFile(String(buf));
}
FakedSliceFile.fromMemory = function (mem, startPos, endPos) {
    return new FakedSliceFile(mem.substring(startPos, endPos));
}

export class FakedFile {
    constructor(filePath) {
        this.size = fs.statSync(filePath).size;
        this.name = path.basename(filePath);
        this.fullPath = filePath;
    }
    slice(startPos, endPos) {
        return FakedSliceFile.fromFile(this.fullPath, startPos, endPos);
    }
}

export class FakedMemoryFile {
    constructor() {
        this.size = 0;
        this.name = "faked-memory-file";
        this.content = '';
    }
    addLine(line) {
        this.content += line;
        this.content += '\n';
        this.size = this.content.length;
        return this;
    }
    slice(startPos, endPos) {
        return FakedSliceFile.fromMemory(this.content, startPos, endPos);
    }
}
